from django.shortcuts import render
from django.http import JsonResponse
from uuapp.models import *


def cart(request):
    return render(request, 'cart.html')


def add_to_cart(request):
    """
    Add goods to shopping cart
    """
    goods_id = request.GET.get('id')
    quantity = int(request.GET.get('quantity', 1))
    
    if not goods_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    try:
        goods = Goods.objects.get(id=goods_id)
    except Goods.DoesNotExist:
        return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
    
    # Initialize cart in session if not exists
    if 'cart' not in request.session:
        request.session['cart'] = {}
    
    cart = request.session['cart']
    
    # Add or update goods in cart
    if goods_id in cart:
        cart[goods_id] += quantity
    else:
        cart[goods_id] = quantity
    
    # Save cart to session
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '添加成功'})


def remove_from_cart(request):
    """
    Remove goods from shopping cart
    """
    goods_id = request.GET.get('id')
    
    if not goods_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    if 'cart' not in request.session or goods_id not in request.session['cart']:
        return JsonResponse({'status': 0, 'errmsg': '商品不在购物车中'}, status=404)
    
    # Remove goods from cart
    del request.session['cart'][goods_id]
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '移除成功'})


def update_cart(request):
    """
    Update quantity of goods in shopping cart
    """
    goods_id = request.GET.get('id')
    quantity = int(request.GET.get('quantity', 1))
    
    if not goods_id:
        return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
    if 'cart' not in request.session or goods_id not in request.session['cart']:
        return JsonResponse({'status': 0, 'errmsg': '商品不在购物车中'}, status=404)
    
    if quantity <= 0:
        return JsonResponse({'status': 0, 'errmsg': '数量必须大于0'}, status=400)
    
    # Update cart quantity
    request.session['cart'][goods_id] = quantity
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '更新成功'})


def checkout(request):
    """
    Process checkout and create order
    """
    if 'cart' not in request.session or not request.session['cart']:
        return JsonResponse({'status': 0, 'errmsg': '购物车为空'}, status=400)
    
    try:
        # Process payment and create order here
        # For now, we'll just clear the cart
        
        # Clear cart after successful checkout
        request.session['cart'] = {}
        request.session.modified = True
        
        return JsonResponse({'status': 1, 'msg': '订单创建成功'})
    except Exception as e:
        return JsonResponse({'status': 0, 'errmsg': str(e)}, status=500)
